<?php
/**
 * Created by PhpStorm.
 * User: dy
 * Date: 2019/12/27
 * Time: 9:08
 */
namespace util;
class TreeUtil
{
    protected static $instance = null;
    private function __construct()
    {
    }
    private function __clone()
    {
    }

    public static function instance(){
        if(empty(self::$instance)){
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * 把返回的数据集转换成Tree
     * @param array $list 要转换的数据集
     * @param string $pid parent标记字段
     * @param string $level level标记字段
     * @return array
     */
    function list_to_tree($list, $pk='id', $pid = 'parent_id', $child = 'child', $root = 0)
    {

        // 创建Tree
        $tree = [];

        if (!is_array($list)) {

            return [];
        }

        // 创建基于主键的数组引用
        $refer = [];

        foreach ($list as $key => $data) {

            $refer[$data[$pk]] =& $list[$key];
        }

        foreach ($list as $key => $data) {

            // 判断是否存在parent
            $parentId =  $data[$pid];

            if ($root == $parentId) {

                $tree[] =& $list[$key];

            } else if (isset($refer[$parentId])){

                is_object($refer[$parentId]) && $refer[$parentId] = $refer[$parentId]->toArray();

                $parent =& $refer[$parentId];

                $parent[$child][] =& $list[$key];
            }
        }

        return $tree;
    }
}